#include <Nordic\reg24le1.h>
#include <stdint.h>
#include "hal_spi.h"
#include "nordic_common.h"

#define LED_PORT P3
#define LED_PORT_DIR P3DIR
#define BUTTON_PORT P2
#define BUTTON_PORT_DIR P2DIR

#define SPI_PACKET_LENGTH 8

bit spi_command_received = 0, radio_idle = 1;
data uint8_t spi_state = 0xFF;
data uint8_t spibuf_out[SPI_PACKET_LENGTH+1], spibuf_in[SPI_PACKET_LENGTH];

// SPI slave initialization function
void simple_spi_slave_init(hal_spi_mode_t mode, hal_spi_byte_order_t bo)
{
  SPISCON0 = 0x00;                        // All interrupts

  switch(mode)                            // Set desired mode
  {
    case HAL_SPI_MODE_0:
      SPISCON0 |= (0x00 << 1);
      break;
    case HAL_SPI_MODE_1:
      SPISCON0 |= (0x01 << 1);
      break;
    case HAL_SPI_MODE_2:
      SPISCON0 |= (0x02 << 1);
      break;
    case HAL_SPI_MODE_3:      
      SPISCON0 |= (0x03 << 1);
      break;
  }
  
  if(bo == HAL_SPI_LSB_MSB)               // Set desired data order
  {
    SPISCON0 |= BIT_3;
  }

  SPISCON0 |= BIT_0;                      // Enable SPI slave
}

void main()
{
  uint8_t temp, i, btn;
  
  simple_spi_slave_init(HAL_SPI_MODE_0, HAL_SPI_MSB_LSB);

  SPI = 1;
  EA = 1;

  while(1)
  {
    if( spi_command_received )
    {
      for( i = 0; i < SPI_PACKET_LENGTH; i++ )
      {
        if( spibuf_in[i] ) temp |= 1 << i;
        spibuf_out[i] = (( btn & (1 << i) )? 1 : 0);
      }
      LED_PORT = temp;
      spi_command_received = 0;
    }
  }  
}
 
void spi_ifp() interrupt INTERRUPT_SERIAL using 1
{
  data uint8_t spi_interrupt_status = SPISSTAT;
  
  if( spi_interrupt_status & 0x01 )  // SPI slave done with transaction
  {
      spibuf_in[spi_state] = SPISDAT;
      if( spi_state < (SPI_PACKET_LENGTH - 2) )
      {
        SPISDAT = spibuf_out[spi_state+2];  
      }
      spi_state++;
  }
  if( spi_interrupt_status & 0x10 )  // CSN low
  {
    spi_state = 0;
    SPISDAT = spibuf_out[1];
  }
  else if( spi_interrupt_status & 0x20 )  // CSN high
  {
      spi_state = 0xFF;
      SPISDAT = spibuf_out[0];
      spi_command_received = 1;
  }
}